package com.powerbank.gateway.config;

import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig;
import io.github.resilience4j.timelimiter.TimeLimiterConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.circuitbreaker.resilience4j.Resilience4JCircuitBreakerFactory;
import org.springframework.cloud.circuitbreaker.resilience4j.Resilience4JConfigBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.cloud.client.circuitbreaker.Customizer;

import java.time.Duration;

/**
 * 熔断器配置
 */
@Slf4j
@Configuration
public class CircuitBreakerConfiguration {

    /**
     * 配置熔断器工厂
     */
    @Bean
    public Customizer<Resilience4JCircuitBreakerFactory> defaultCustomizer() {
        return factory -> {
            // 默认配置
            factory.configureDefault(id -> new Resilience4JConfigBuilder(id)
                    .circuitBreakerConfig(getDefaultCircuitBreakerConfig())
                    .timeLimiterConfig(getDefaultTimeLimiterConfig())
                    .build());
            
            // 用户服务熔断器配置
            factory.configure(builder -> builder
                    .circuitBreakerConfig(getUserServiceCircuitBreakerConfig())
                    .timeLimiterConfig(getDefaultTimeLimiterConfig()), "user-service");
            
            // 支付服务熔断器配置
            factory.configure(builder -> builder
                    .circuitBreakerConfig(getPaymentServiceCircuitBreakerConfig())
                    .timeLimiterConfig(getDefaultTimeLimiterConfig()), "payment-service");
            
            // 订单服务熔断器配置
            factory.configure(builder -> builder
                    .circuitBreakerConfig(getOrderServiceCircuitBreakerConfig())
                    .timeLimiterConfig(getDefaultTimeLimiterConfig()), "order-service");
        };
    }

    /**
     * 默认熔断器配置
     */
    private CircuitBreakerConfig getDefaultCircuitBreakerConfig() {
        return CircuitBreakerConfig.custom()
                // 失败率阈值 50%
                .failureRateThreshold(50.0f)
                // 慢调用率阈值 50%
                .slowCallRateThreshold(50.0f)
                // 慢调用时间阈值 3秒
                .slowCallDurationThreshold(Duration.ofSeconds(3))
                // 最小调用次数 10次
                .minimumNumberOfCalls(10)
                // 滑动窗口大小 10次调用
                .slidingWindowSize(10)
                // 半开状态允许的调用次数
                .permittedNumberOfCallsInHalfOpenState(3)
                // 熔断器开启持续时间 30秒
                .waitDurationInOpenState(Duration.ofSeconds(30))
                // 自动从开启状态转换到半开状态
                .automaticTransitionFromOpenToHalfOpenEnabled(true)
                // 记录异常
                .recordExceptions(Exception.class)
                // 忽略异常
                .ignoreExceptions(IllegalArgumentException.class)
                .build();
    }

    /**
     * 用户服务熔断器配置
     */
    private CircuitBreakerConfig getUserServiceCircuitBreakerConfig() {
        return CircuitBreakerConfig.custom()
                .failureRateThreshold(60.0f)
                .slowCallRateThreshold(60.0f)
                .slowCallDurationThreshold(Duration.ofSeconds(2))
                .minimumNumberOfCalls(5)
                .slidingWindowSize(10)
                .permittedNumberOfCallsInHalfOpenState(3)
                .waitDurationInOpenState(Duration.ofSeconds(20))
                .automaticTransitionFromOpenToHalfOpenEnabled(true)
                .build();
    }

    /**
     * 支付服务熔断器配置（更严格）
     */
    private CircuitBreakerConfig getPaymentServiceCircuitBreakerConfig() {
        return CircuitBreakerConfig.custom()
                .failureRateThreshold(30.0f)
                .slowCallRateThreshold(30.0f)
                .slowCallDurationThreshold(Duration.ofSeconds(2))
                .minimumNumberOfCalls(8)
                .slidingWindowSize(15)
                .permittedNumberOfCallsInHalfOpenState(2)
                .waitDurationInOpenState(Duration.ofSeconds(60))
                .automaticTransitionFromOpenToHalfOpenEnabled(true)
                .build();
    }

    /**
     * 订单服务熔断器配置
     */
    private CircuitBreakerConfig getOrderServiceCircuitBreakerConfig() {
        return CircuitBreakerConfig.custom()
                .failureRateThreshold(40.0f)
                .slowCallRateThreshold(40.0f)
                .slowCallDurationThreshold(Duration.ofSeconds(4))
                .minimumNumberOfCalls(10)
                .slidingWindowSize(12)
                .permittedNumberOfCallsInHalfOpenState(3)
                .waitDurationInOpenState(Duration.ofSeconds(45))
                .automaticTransitionFromOpenToHalfOpenEnabled(true)
                .build();
    }

    /**
     * 默认超时配置
     */
    private TimeLimiterConfig getDefaultTimeLimiterConfig() {
        return TimeLimiterConfig.custom()
                .timeoutDuration(Duration.ofSeconds(5))
                .build();
    }
}